import { User } from '../db/entity/user.entity.js';

export async function register(username: string, password: string, description: string="") {
    const user = await User.findUserByUserName(username)
    if (user) {
        throw new Error('用户名已存在')
    }
    await User.createUser({
        userName: username,
        password: password,
        description: description
    });
}

//使用User完成登录
export async function login(username:string, password:string) {
    const user = await User.findUserByUserName(username)
    if (user && user.password === password) {
        //设置token
        user.token = User.generateToken()
        await User.setToken(user.id,user.token)
        return user
    }else {
        return null
    }
}
/**
 * 
 * @param token 注销登录
 * @param userId
 * @returns 
 */
export async function logout(userId:number) {
    User.setToken(userId,'')
}
// 新增根据token获取用户信息的服务函数
export async function getUserByToken(token: string) {
    const user = await User.getUserByToken(token);
    if (!user) {
        return null;
    }
    const { password,...rest } = user;
    return rest;

}

// 新增更新用户的服务函数
export async function updateUser(userId: number, updatedData: Partial<User>) {
    const user = await User.findUserById(userId);
    if (!user) {
        return null;
    }
    Object.assign(user, updatedData);
    return await User.updateUser(userId, user);
}

// 新增分页查询用户的服务函数
export async function getUsersByPage(page: number = 1, pageSize: number = 10,username = '') {
    return await User.findUsersByUsernameWithPagination(page, pageSize,username);
}


// // 新增分页查询用户的服务函数
// export async function getUsersByPage(page: number = 1, pageSize: number = 10) {
//     const [items, total] = await User.findAndCount({
//         skip: (page - 1) * pageSize,
//         take: pageSize
//     });
//     const pages = Math.ceil(total / pageSize);

//     // 移除每个用户对象中的 password 字段
//     const sanitizedItems = items.map(user => {
//         const { password, ...rest } = user;
//         return rest;
//     });

//     return {
//         items: sanitizedItems,
//         total,
//         page,
//         pageSize,
//         pages
//     };
// }

// 新增根据id获取用户信息的服务函数，返回数据不包含password
export async function getUserById(id: number) {
    const user = await User.findUserById(id);
    if (!user) {
        return null;
    }
    const { password,token, ...rest } = user;
    return rest;
}

// 获取用户发布todo数量统计信息
export async function getUserTodoCount(userId: number) {
    const user = await User.findUserById(userId);
    if (!user) {
        return null;
    }
    let res = await User.getTodoCountByUserId(userId)
    return res;
}